package site.syksy.qingzhou.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import site.syksy.qingzhou.common.properties.QingZhouProperties;
import site.syksy.qingzhou.security.authentication.GeneralLogoutSuccessHandler;
import site.syksy.qingzhou.upms.service.UserService;

import javax.annotation.Resource;
import java.util.Set;

import static site.syksy.qingzhou.security.authentication.GeneralAuthenticationDsl.generalDsl;

/**
 * @author Raspberry
 * Web权限配置
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userService;

    @Resource
    QingZhouProperties qingZhouProperties;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .apply(generalDsl())
                .setLoginUrl("/qz/api/login/account").setUserService(userService)
                .and()
                .logout().logoutUrl("/qz/api/login/outLogin").logoutSuccessHandler(new GeneralLogoutSuccessHandler());
        http.sessionManagement().maximumSessions(1).expiredUrl("/qz/api/login/account").maxSessionsPreventsLogin(true);
    }

    @Override
    public void configure(WebSecurity web) {
        QingZhouProperties.Security security = qingZhouProperties.getSecurity();
        if (security != null) {
            Set<String> webIgnoring = security.getWebIgnoring();
            if (webIgnoring != null) {
                web.ignoring().antMatchers(webIgnoring.toArray(new String[0]));
            }
        }
    }

}
